package cn.ratel.route;

import com.google.common.base.Preconditions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class RenderProvider {
	private static Render defaultRender = DefaultRenders.JSON;
	private static Map<Class<?>, Render> renderMap = new HashMap<Class<?>, Render>() {
		{
			for (RenderProvider.Render render : DefaultRenders.values()) {
				Class<?> supportType = render.getSupportType();
				Preconditions.checkArgument(supportType != Object.class, "method getSupportTypes of Render can not return Object.class : " + render);
				put(supportType, render);
			}
			remove(defaultRender.getClass());
		}
	};

	private RenderProvider() {
	}

	public static Render getRender(Class<?> clazz) {
		Render render = renderMap.get(clazz);
		return render == null ? defaultRender : render;
	}

	public interface Render {
		void render(HttpServletRequest req, HttpServletResponse res, Object result);

		Class<?> getSupportType();
	}

	public static void addRender(Render render) {
		renderMap.put(render.getSupportType(), render);
	}

	public static void setDefaultRender(Render defaultRender) {
		RenderProvider.defaultRender = defaultRender;
		renderMap.remove(defaultRender.getClass());
	}
}
